package com.winning.bdu.dl.jdbc;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


/**
 * @Author: yanxf@winning.com.cn
 * @Description: 批量导入工具类
 * @Date 2019/05/15 15:32
 */
@Component
public class BatchInsertUtils {
    private Logger logger = LoggerFactory.getLogger( getClass() );

    @Resource
    private JdbcTemplateRepository jdbcTemplateRepository;

    private int defaultSize = 200;

    /**
     * 批量插入数据
     *
     * @param jsonStr   json字符串
     * @param tableName 表名
     * @throws Exception
     */
    public void execute(String jsonStr, String tableName) throws Exception {

        List<Map<String, Object>> datas = (List<Map<String, Object>>) JSON.parse( jsonStr );
        execute( datas, tableName, defaultSize );
    }

    /**
     * 批量插入数据
     *
     * @param datas     更新对象集合
     * @param tableName 表名
     * @throws Exception
     */
    public void execute(List<Map<String, Object>> datas, String tableName) throws Exception {

        execute( datas, tableName, defaultSize );
    }

    /**
     * 批量插入数据
     *
     * @param datas     更新对象集合
     * @param tableName 表名
     * @param size      批量sql条数
     */
    public void execute(List<Map<String, Object>> datas, String tableName, int size) throws Exception {

        List<String> batchSQL = buildSQL( datas, tableName, size );

        if (CollectionUtils.isEmpty( batchSQL )) {
            return;
        }
        for (String sql : batchSQL) {
            logger.debug( sql );


            jdbcTemplateRepository.getJdbcTemplate().execute( sql );

        }
    }

    /**
     * 创建批量sql
     *
     * @return
     */
    private List<String> buildSQL(List<Map<String, Object>> datas, String tableName, int splitSize) throws Exception {

        if (CollectionUtils.isEmpty( datas )) {
            return null;
        }
        List<String> batchSQLs = new ArrayList<>();
        Map<String, Object> headerMap = datas.get( 0 );
        String headerSql = createInsertHeader( tableName, headerMap );
        int dateSize = datas.size();
        int pageNum = 1;
        StringBuilder fieldSb = new StringBuilder();
        Iterator<Map<String, Object>> iterator = datas.iterator();
        for (int i = 0; iterator.hasNext(); i++) {
            int offSet = (dateSize - (splitSize * (pageNum - 1))) > splitSize ? splitSize * pageNum : dateSize;

            fieldSb.append( createInsertValue( iterator.next(), headerMap ) );
            if ((offSet - 1) == i) {
                String fieldStr = StringUtils.substringBeforeLast( fieldSb.toString(), "," );
                batchSQLs.add( headerSql + fieldStr );
                pageNum++;
                fieldSb.setLength( 0 );
            }
        }
        return batchSQLs;
    }

    /**
     * 创建取值sql
     *
     * @return
     * @throws Exception
     */
    private StringBuilder createInsertValue(Map<String, Object> dataMap, Map<String, Object> headerMap) throws Exception {

        StringBuilder fieldSb = new StringBuilder( "(" );

        int index = 1;
        for (Map.Entry<String, Object> entry : headerMap.entrySet()) {

            Object value = dataMap.get( entry.getKey() );
            if (value instanceof String) {
                String valuestr = String.valueOf( value );
                valuestr = StringUtils.replaceEach( valuestr, new String[]{"'"}, new String[]{"\\'"} );
                fieldSb.append( "'" ).append( valuestr ).append( "'" );
            } else {
                fieldSb.append( value );
            }

            if (index < headerMap.size()) {
                fieldSb.append( "," );
            }
            index++;
        }
        fieldSb.append( ")," );
        return fieldSb;
    }


    /**
     * 创建头部sql
     *
     * @throws Exception
     */
    private String createInsertHeader(String tableName, Map<String, Object> headerMap) throws Exception {

        StringBuilder fieldSb = new StringBuilder();
        headerMap.forEach( (key, value) -> fieldSb.append( key + ", " ) );
        String fieldStr = StringUtils.substringBeforeLast( fieldSb.toString(), "," );
        String headerSql = "INSERT INTO " + StringUtils.uncapitalize( tableName ) + "(" + fieldStr + ") VALUES ";
        return headerSql;
    }


}
